package android.snake;

import java.util.ArrayList;
import java.util.Iterator;

import android.snake.SnakeUtils.Direction;
import android.util.Pair;

public class Reptile {

	//List used to held all parts of the snake in the order.
	private ArrayList< Pair<Integer, Integer> > reptile_;
	
	public Reptile (int x, int y)
	{
		reptile_ = new ArrayList< Pair<Integer, Integer> >();
		reptile_.clear();
		reptile_.add(0, Pair.create(x, y));
	} 
			
	private SnakeUtils.Direction lastDirection;

	// Move the reptile in the given direction.
	// Return false if invalid move
	public boolean moveReptile (SnakeUtils.Direction direction, Board b)
	{
		int goto_x = getReptileHead().first;
		int goto_y = getReptileHead().second;
		int head_x = getReptileHead().first;
		int head_y = getReptileHead().second;

		// Check for 'out-of-bounds' issues
		if (direction == Direction.right)
			if (head_x == b.getX() - 1)
				return false;
			else
				goto_x++;

		if (direction == Direction.left)
			if (head_x == 0)
				return false;
			else
				goto_x--;

		if (direction == Direction.down)
			if (head_y == b.getX() - 1)
				return false;
			else
				goto_y++;

		if (direction == Direction.up)
			if (head_y == 0)
				return false;
			else
				goto_y--;

		// FIXME: The reptile can't lose with that for now !
		if (b.getBoard()[goto_x][goto_y] != Case.empty)
			return false;

		// Move and update all the reptile tail
		for (int i = 1; i < reptile_.size(); i++)
			this.reptile_.set(i, reptile_.get(i - 1));

		// Move the head of the reptile to the new position
		this.reptile_.set(0, Pair.create(goto_x, goto_y));

		//Clear the board
		for (Integer i = 1; i < b.getX() - 1; i++)
			for (Integer j = 1; j < b.getX() - 1; j++)
				b.getBoard()[i][j] = Case.empty;

		// Refresh the cells of the board
		for (Iterator<Pair<Integer, Integer> > it = reptile_.iterator();
			it.hasNext(); )
		{
			Pair<Integer, Integer> pos = it.next();
			b.getBoard()[pos.first][pos.second] = Case.snake;
        }
		
		return true;
	}

	// Move the reptile using the last direction given to it
	public void moveReptile (Board b)
	{
		moveReptile (lastDirection, b);
	}

	// Destroy the reptile
	public void destroyReptile ()
	{
		reptile_.clear();
	}

	public boolean isPartOfReptile (int x, int y)
	{
		for (int i = 0; i < reptile_.size(); i++)
			if ((reptile_.get(i).first == x) && (reptile_.get(i).second == y))
				return true;

		return false;
	}

	// After this comment, getters and setters

	public void setReptile(ArrayList< Pair<Integer, Integer> > snake_) {
		this.reptile_ = snake_;
	}

	public ArrayList< Pair<Integer, Integer> > getReptile() {
		return reptile_;
	}

	public Pair<Integer, Integer> getReptileHead() {
		return reptile_.get(0);
	}

}
